#!/usr/bin/env python
# encoding: utf-8

import os
import wsgiref.handlers
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
import models
import cgi

class MainHandler(webapp.RequestHandler):
  def get(self):
    values = {}
    tmpl_file = ''

    if users.get_current_user():
      values['url'] = users.create_logout_url(self.request.uri)
      tmpl_file = 'main.html'
    else:
      values['url'] = users.create_login_url(self.request.uri)
      tmpl_file = 'index.html'

    path = os.path.join(os.path.dirname(__file__), 'templates', tmpl_file)
    self.response.out.write(template.render(path, values))

class ProjectNewHandler(webapp.RequestHandler):
  @login_required
  def get(self):
    values = {}
    tmpl_file = 'project_new.html'
    
    values['logout_url'] = users.create_logout_url(self.request.uri)
    
    path = os.path.join(os.path.dirname(__file__), 'templates', tmpl_file)
    self.response.out.write(template.render(path, values))

  def post(self):
    app_user = users.get_current_user()
    if not app_user:
      self.redirect(users.create_login_url(self.request.uri))
      return

    user = models.User.gql("WHERE user = :1", app_user).get()
    
    if not user:
      user = models.User(name = app_user.nickname(), user = app_user)
      user.put()
    
    p = models.Project(
      name = cgi.escape(self.request.get('name')),
      manager = user)
    p.put()
    
    self.response.headers.add_header('Set-Cookie', 'created=project; ')
    
    self.redirect('/project/' + str(p.key().id()))

class ProjectViewHandler(webapp.RequestHandler):
  @login_required
  def get(self, key):
    values = {}
    tmpl_file = 'project.html'
    
    p = models.Project.get_by_id(int(key))
    
    values['logout_url'] = users.create_logout_url(self.request.uri)
    values['project'] = p.name
    values['manager'] = p.manager.name
    
    if self.request.cookies.get('created') == 'project':
      self.response.headers.add_header('Set-Cookie', 'created=; ')
      values['message'] = 'Projekat je uspješno napravljen'
    
    path = os.path.join(os.path.dirname(__file__), 'templates', tmpl_file)
    self.response.out.write(template.render(path, values))

def application():
  return webapp.WSGIApplication([
      ('/', MainHandler),
      ('/project/new', ProjectNewHandler),
      ('/project/([0-9]+)', ProjectViewHandler)
    ], debug=True)

def main():
  wsgiref.handlers.CGIHandler().run(application())

if __name__ == '__main__':
  main()
